package com.moter.demo01.juc.alllocks.fairlock;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class UnfairLock {
    private volatile LinkedBlockingQueue<Thread> lock = new LinkedBlockingQueue<>();
    private volatile int state ;
    public UnfairLock(){
        state=0;
    }
    public void lock(){
        if(state==0){

        }else{
            Thread thread = Thread.currentThread();
            try {

                lock.put(thread);
                LockSupport.park();//
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        state=1;

    }
    public void unlock(){
        if(lock.size()>0){
            try {
                Thread take = lock.take();
                System.out.println(take.getName());
                LockSupport.unpark(take);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        state=0;
    }

    public static void main(String[] args) throws InterruptedException {
        UnfairLock unfairLock = new UnfairLock();
        for (int i = 0; i <10 ; i++) {
            int finalI = i;
            new Thread(()-> {
                unfairLock.lock();
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    unfairLock.unlock();
                }
            },i+"").start();
        }
    }

}
